package com.itheima.filter;

import com.itheima.bean.Employee;
import com.itheima.bean.User;
import com.itheima.config.ThreadLocalConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.server.Session;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class DengLuFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        if (uri.contains("login") || uri.contains("logout") || uri.endsWith(".js") || uri.endsWith(".png") || uri.endsWith("jpg") ||
                uri.endsWith(".css") || uri.contains("ico") || uri.contains("fonts")||uri.contains("sms")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        Employee employee = (Employee) request.getSession().getAttribute("employee");
        if (employee != null) {
            ThreadLocalConfig.set(employee.getId());
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        User user = (User)request.getSession().getAttribute("user");
        if (user != null) {
            ThreadLocalConfig.set(user.getId());
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        response.sendRedirect("/backend/page/login/login.html");
    }
}
